package com.kh.chart;

import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.ui.Layer;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.data.general.DatasetUtils;

import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.util.Collection;
import java.util.List;

public class WaveChartPanel extends ChartPanel {

    public WaveChartPanel(JFreeChart freeChart) {
        super(freeChart);
        this.setPopupMenu(null);
    }

    private double getDomainValue(int x) {
        final Rectangle2D screenDataArea = getScreenDataArea();
        final JFreeChart chart = getChart();
        final CombinedDomainXYPlot plot = (CombinedDomainXYPlot) chart.getPlot();
        final ValueAxis domainAxis = plot.getDomainAxis();
        double d = domainAxis.java2DToValue(x, screenDataArea, RectangleEdge.BOTTOM);
        if (!domainAxis.getRange().contains(d)) {
            d = (0.0D / 0.0D);
        }
        return d;
    }

    private void setSolidMarkerValue(double value) {
        final JFreeChart chart = getChart();
        final CombinedDomainXYPlot plot = (CombinedDomainXYPlot) chart.getPlot();
        final List<XYPlot> subplots = (List<XYPlot>) plot.getSubplots();
        for (XYPlot subPlot : subplots) {
            double d1 = DatasetUtils.findYValue(subPlot.getDataset(), 0, value);
            final Collection domainMarkers = subPlot.getDomainMarkers(0, Layer.FOREGROUND);
            final Object[] objects = domainMarkers.toArray();
            if (objects != null && objects.length > 0) {
                ((ValueMarker) objects[0]).setValue(value);
            }
        }
    }

    private void setDashMarkerValue(double value) {
        final JFreeChart chart = getChart();
        final CombinedDomainXYPlot plot = (CombinedDomainXYPlot) chart.getPlot();
        final List<XYPlot> subplots = (List<XYPlot>) plot.getSubplots();
        for (XYPlot subPlot : subplots) {
            double d1 = DatasetUtils.findYValue(subPlot.getDataset(), 0, value);
            final Collection domainMarkers = subPlot.getDomainMarkers(0, Layer.FOREGROUND);
            final Object[] objects = domainMarkers.toArray();
            if (objects != null && objects.length > 1) {
                ((ValueMarker) objects[1]).setValue(value);
            }
        }
    }

    @Override
    public void mouseClicked(MouseEvent event) {
        double d = getDomainValue(event.getX());
        if (event.getButton() == MouseEvent.BUTTON1) {
            setSolidMarkerValue(d);
        } else if (event.getButton() == MouseEvent.BUTTON3) {
            setDashMarkerValue(d);
        }
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        double d = getDomainValue(e.getX());
        setSolidMarkerValue(d);
    }
}
